package com.example.ioapp;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends Activity implements Runnable{

      Button savebtn,readbtn,savesdcard,readsdcard;
      TextView text;
      EditText edit;
      String str;
      String fileName = "text.txt";

      private View arg0;

    public MainActivity(View arg0) {
        this.arg0 = arg0;
    }

    @Override
    public void run() {
        mClick click = new mClick();
        click.onClick(arg0);
    }

    public void main(String[] args) {
        MainActivity t1 = new MainActivity(savebtn);
        MainActivity t2 = new MainActivity(readbtn);
        MainActivity t3 = new MainActivity(savesdcard);
        MainActivity t4 = new MainActivity(readsdcard);

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
        new Thread(t4).start();
    }

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          //初始化组件
          edit = (EditText)findViewById(R.id.editText1);
          text = (TextView)findViewById(R.id.textView1);

          savebtn = (Button)findViewById(R.id.button1);
          savebtn.setOnClickListener(new mClick());

          readbtn = (Button)findViewById(R.id.button2);
          readbtn.setOnClickListener(new mClick());

          savesdcard = (Button)findViewById(R.id.button3);
          savesdcard.setOnClickListener(new mClick());

          readsdcard = (Button)findViewById(R.id.button4);
          readsdcard.setOnClickListener(new mClick());

    }

    //按钮事件
    class mClick implements OnClickListener {
        @Override
        public void onClick(View arg0) {
            if (arg0 == savebtn){
                savefile();
            }else if(arg0 == readbtn){
                readfile(fileName);
            }else if(arg0 == savesdcard){
                setRegist();
                savesdcard();
            }else if(arg0 == readsdcard){
                readsdcard(fileName);
            }
        }
    }


    //写入文件
    void savefile(){
          //获取输入的内容
          str = edit.getText().toString();
          FileOutputStream f_out = null;
          try{
              //创建文本输出流
              f_out = openFileOutput(fileName, Context.MODE_PRIVATE);
              //按字节输出数据到文件中
              f_out.write(str.getBytes());
              Toast.makeText(MainActivity.this,"文件已保存",Toast.LENGTH_LONG).show();
          }catch (FileNotFoundException e){
              e.printStackTrace();
          }catch (IOException e){
              e.printStackTrace();
          }finally{
              try{
                  if(f_out != null){
                      f_out.close();
                  }
              }catch (Exception ex){
                  ex.printStackTrace();
              }
          }
    }
    //读取文件
    void readfile(String fileName){
        byte[] buffer = new byte[1024];
        FileInputStream f_in = null;
        try{
            f_in = openFileInput(fileName);
            int bytes = f_in.read(buffer);
            str = new String(buffer,0,bytes);
            text.setText(str);
            Toast.makeText(MainActivity.this,"文件内容：" +str,Toast.LENGTH_LONG).show();
        }catch (FileNotFoundException e){
            System.out.print("文件不存在！");
        }catch (IOException e){
            System.out.print("IO流错误！");
        }finally{
            try{
                if(f_in != null){
                    f_in.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }
    //写入到sd卡中
    void savesdcard(){
        //获取输入的内容
        str = edit.getText().toString();
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //获取sd卡的路径
            File path = Environment.getExternalStorageDirectory();
            File sdfile = new File(path,fileName);
            FileOutputStream out_file = null;
            try{
                //创建文本输出流
                out_file = new FileOutputStream(sdfile);
                //按字节输出数据到文件中
                out_file.write(str.getBytes());
                Toast.makeText(MainActivity.this,"文件保存到SD卡",Toast.LENGTH_LONG).show();
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }finally{
                try{
                    if(out_file != null){
                        out_file.close();
                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    //读取sd卡中的内容
    void readsdcard(String fileName){
          //判断是否允许读写操作
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File path = Environment.getExternalStorageDirectory();
            File sdfile = new File(path,fileName);
            FileInputStream in_file = null;
            try{
                in_file = new FileInputStream(sdfile);
                byte[] buffer = new byte[1024];
                //读取文件数据到字节数组
                int bytes = in_file.read(buffer);
                str = new String(buffer,0,bytes);
                text.setText(str);
                Toast.makeText(MainActivity.this,"SD卡读取到的数据为：" +str,Toast.LENGTH_LONG).show();
            }catch (FileNotFoundException e){
                System.out.print("文件不存在！");
            }catch (IOException e){
                System.out.print("IO流错误！");
            }finally{
                try{
                    if(in_file != null){
                        in_file.close();
                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    //动态获取权限
    public void setRegist() {
          //大于23是指Android 6.0以后的版本
        if(Build.VERSION.SDK_INT >=23){
            int REQUEST_CODE_CONTACT = 101;
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for(String str : PERMISSIONS_STORAGE){
                if(this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED){
                    //申请权限
                    this.requestPermissions(PERMISSIONS_STORAGE,REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
    }
}


